/**
 * 管理界面模板入口文件
 * */
import React, { useCallback, useImperativeHandle, useMemo, useState } from 'react';
import { Card, Form } from 'antd';
import cls from 'classnames';
import { TableLayout, ActionButtons, CommonTable, SchemaManageLayout, FilterDrawer, SearchBox, SearchLayout } from './components';

import { useSearchProps, useTableProps } from './hooks';
import { SchemaManageAPI } from '@/components/SchemaComponent/SchemaManage/type';
import _ from 'lodash';

const getKey = () => {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};

export const SchemaManage = React.forwardRef((props: SchemaManageAPI.ISchemaManageProps, ref) => {
  const [visibleFilter, setVisibleFilter] = useState<boolean>(false);
  const [filterInitValue, setFilterInitValue] = useState({});
  const [form] = Form.useForm();
  // 保存当前选中权限
  const [switchOpt, setSwitch] = useState<{
    key?: any;
    params?: Record<string, any>;
  }>({
    key: '',
    params: {},
  }); //选中的头部切换key值

  const { searchProps } = useSearchProps(props?.searchProps);

  const { dispatch, tableProps } = useTableProps(props?.tableProps, switchOpt);

  /* 修改显示列 */
  const screenColumns = useCallback(
    (columns: any) => {
      dispatch({
        type: 'screenColumns',
        payload: {
          columns,
        },
      });
    },
    [props],
  );

  /**
   * 自动触发搜索
   * 确认要设置的默认值是在外层还是隐藏起来了，外层的就传第一个参数，隐藏起来的传第二个参数
   * @param {Object} formObj 默认展示的搜索条件
   * @param {Object} drawFormObj 隐藏的搜索条件
   * */
  const setSearch = (formObj, drawFormObj?: Record<string, any>) => {
    form.setFieldsValue(formObj);
    if (drawFormObj) {
      setFilterInitValue(drawFormObj);
    }
    let FormValues = _.cloneDeep(form.getFieldsValue());
    let searchValue = screenValues({ ...FormValues });
    let allValues = {
      ...switchOpt?.params,
      ...searchValue,
    };
    setTimeout(function () {
      searchProps?.onSearch(allValues);
    }, 10);
  };

  /** ref 导出改变默认选中标签 */
  useImperativeHandle(ref, () => ({
    setSwitch: setSwitch,
    setSearch: setSearch,
  }));

  /* 关闭filterDrawer */
  const onCloseFilter = useCallback(() => {
    setVisibleFilter(false);
  }, [visibleFilter]);

  /* 打开filterDrawer */
  const onOpenFilter = useCallback(() => {
    setVisibleFilter(true);
  }, [visibleFilter]);

  // 判断是否有高级搜索的数据
  const isHaveSeniorSearch = () => {
    let isBool: boolean = searchProps?.searchList?.some((item: any) => {
      return item?.whetherSenior == true;
    });
    return isBool;
  };

  /* 筛选搜索需要的值 */
  const screenValues = (values: any) => {
    let newValues: any = {};
    if (values) {
      Object?.keys(values).forEach((item) => {
        if (values?.[item] || values?.[item] >= 0) {
          newValues[item] = values?.[item];
        }
      });
    }

    return newValues;
  };

  /* 搜索方法 */
  const onSearchClick = () => {
    let FormValues = _.cloneDeep(form.getFieldsValue());
    let searchValue = screenValues({ ...FormValues });
    let allValues = {
      ...switchOpt?.params,
      ...searchValue,
    };

    searchProps?.onSearch(allValues);
  };

  return (
    <SchemaManageLayout Table={tableProps} Search={searchProps} SearchRenderProps={props?.searchRenderProps}>
      <SearchLayout>
        <SearchBox
          onOpenFilter={onOpenFilter}
          isShowSeniorBtn={isHaveSeniorSearch()}
          switchOpt={switchOpt}
          setSwitch={setSwitch}
          form={form}
          onSearchClick={onSearchClick}
        />
      </SearchLayout>
      <TableLayout>
        <Card className={cls('list-layout-tableCard')}>
          {props?.tableRenderProps?.otherTableCol ? (
            <>
              {!props?.myWorkbenchType && <ActionButtons actionList={props?.actionList} screenColumns={screenColumns} />}
              {props?.tableRenderProps?.component}
            </>
          ) : (
            <>
              {!props?.myWorkbenchType && <ActionButtons actionList={props?.actionList} screenColumns={screenColumns} />}
              <CommonTable />
            </>
          )}
        </Card>
        <FilterDrawer filterInitValue={filterInitValue} searchDrawerRender={props?.searchDrawerRender} visible={visibleFilter} onClose={onCloseFilter} />
      </TableLayout>
    </SchemaManageLayout>
  );
});

SchemaManage.displayName = `Schema-manage-${getKey()}-${getKey()}`;
SchemaManage.defaultProps = {};
